package com.lenovo.lmrp.server.appgateway.util;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;
import java.util.Map;

import com.lenovo.sdc.framework.util.exception.ErrorCode;
import com.lenovo.sdc.framework.util.exception.TraceableException;
import com.mitchellbosecke.pebble.PebbleEngine;
import com.mitchellbosecke.pebble.error.PebbleException;
import com.mitchellbosecke.pebble.loader.FileLoader;
import com.mitchellbosecke.pebble.template.PebbleTemplate;

public class PageLoader {
    public static final String PATH_KEY = "view.path";

    private static PebbleEngine pebbleEngine;
    /**
     * 初始化模版引擎
     */
    static {
        String path = PropertiesUtil.getStringValue(PATH_KEY);
        URL u = ClassLoader.getSystemResource("");
        path = new File(u.getFile(), path).getAbsolutePath();
        FileLoader fLoader = new FileLoader();
        fLoader.setPrefix(path);
        pebbleEngine = new PebbleEngine.Builder().loader(fLoader).build();
    }

    /**
     * 获取解析后模版
     * @author suo
     * @param key     模版路径
     * @param context 模板值
     * @return
     */
    public static String getPage(String key, Map<String, Object> context) {
        String output = null;
        try (Writer writer = new StringWriter()) {
            PebbleTemplate pebbleTemp = pebbleEngine.getTemplate(key);
            pebbleTemp.evaluate(writer, context);
            output = writer.toString();
        }
        catch (PebbleException | IOException e) {
            throw new TraceableException(ErrorCode.FILE_NOTFOUND, e);
        }
        return output;
    }

}
